package com.rec.smile.ui;

import static com.rec.smile.ImageUtil.groundImage;

import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JPanel;

public class CrPanel extends JPanel {

	static int gapWidth = 0;
	static int gapHeight = 0;

	static final int w = 20, h = 20;


	private List<Actor> actors = null;
	
	private Tower tower;
	
	public static final int startX;
	public static final int endX;
	public static final int startY;
	public static final int endY;

	static{
		gapWidth = groundImage.getWidth(null);
		gapHeight = groundImage.getHeight(null);
		startX = w * gapWidth / 2 - w * gapWidth / 4;
		endX = w * gapWidth / 2 + w * gapWidth / 4;
		startY = h * gapHeight / 2 - h * gapHeight / 4;
		endY = h * gapHeight / 2 + h * gapHeight / 4;
		
	}
	
	public CrPanel() {
		super();
		setSize(w * gapWidth, h * gapHeight);
		actors = new ArrayList<Actor>(1);
		Random r = new Random();
		for (int i = 0; i < 2; i++) {
			Actor actor = new Actor(r.nextInt(w * gapWidth - gapWidth), r.nextInt(h
					* gapHeight - gapHeight));
			actors.add(actor);
		}
		tower = new Tower(w * gapWidth/4, h * gapHeight/4);
//		actor.walk();
		
		new Thread(new Runnable() {
			
			public void run() {
				try {
					while(true){
						Thread.sleep(200);
						repaint();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		for (int i = 0; i < w * h; i++) {
			g.drawImage(groundImage, i % w * gapWidth, i / h * gapHeight, null);
		}

		for (int i = 0; i < actors.size(); i++) {
			actors.get(i).draw(g);
		}
		
//		tower.draw(g);
	}

	public void start(){
		walk();
		meetAndAttack();
	}
	
	public List<Actor> getActors() {
		return actors;
	}

	public void meetAndAttack() {
//		for(int i = 0; i < actors.size() - 1;i++){
//			for (int j = i + 1; j < actors.size(); j++) {
//				attack(i,j);
//			}
//		}
		attack(0, 1);
	}

	public void walk(){
		for (Actor actor : actors) {
			actor.walk();
		}
	}
	
	private void attack(int i, int j) {
		if(actors.isEmpty())
			return;
		if(actors.size() <= i  || actors.size() <= j){
			return ;
		}
		if(actors.get(i).meet(actors.get(j))){
			if(actors.get(i).descHp((int) (10 +  Math.random() * 100))){
				actors.get(j).startWalking();
				actors.remove(i);
				return ;
			}
			if(actors.get(j).descHp((int) (10 +  Math.random() * 100))){
				actors.get(i).startWalking();
				actors.remove(j);
			}
		}
	}
}
